import type { LoginAndRegisterParams } from '@vben/common-ui';
import type { UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { ElNotification } from 'element-plus';
import { defineStore } from 'pinia';

import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore(
  'auth',
  () => {
    const accessStore = useAccessStore();
    const userStore = useUserStore();
    const router = useRouter();

    const loginLoading = ref(false);

    /**
     * 异步处理登录操作
     * Asynchronously handle the login process
     * @param params 登录表单数据
     */
    async function authLogin(
      params: LoginAndRegisterParams,
      onSuccess?: () => Promise<void> | void,
    ) {
      // 异步处理用户登录操作并获取 accessToken
      let userInfo = null;
      try {
        loginLoading.value = true;
        // console.log('login params', params)
        const data = await loginApi(params);
        console.log('xxxxxxxxxxxxxxxxxxxxxxdata', data);

        // Object.assign(data, {
        //   accessToken:
        //     'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MCwicGFzc3dvcmQiOiIxMjM0NTYiLCJyZWFsTmFtZSI6IlZiZW4iLCJyb2xlcyI6WyJzdXBlciJdLCJ1c2VybmFtZSI6InZiZW4iLCJpYXQiOjE3MzQ4NTIyODQsImV4cCI6MTczNTQ1NzA4NH0.cX3PclTvrvw8CLHNEPk9WRIXUNunXA_HkD2_DNo9lTk',
        // });
        const accessToken = data[0].token;

        // 如果成功获取到 accessToken
        if (accessToken) {
          // 将 accessToken 存储到 accessStore 中
          accessStore.setAccessToken(accessToken);
          userInfo = {
            realName: data[0].username,
            roles: [data[0].accesstype],
            username: data[0].username,
          };

          userStore.setUserInfo(userInfo);
          accessStore.setAccessCodes([
            'AC_100100',
            'AC_100110',
            'AC_100120',
            'AC_100010',
          ]);
          console.log('userInfo', userInfo);
          if (
            userInfo.roles[0] == 'AC100000' ||
            userInfo.roles[0] == 'AC100001'
          ) {
            router.push('/closed-management/access-control/personnel-passage');
          } else if (userInfo.roles[0] == 'AC100010') {
            router.push('/closed-management/entry-exit/personnel-review');
          } else if (userInfo.roles[0] == 'AC999999') {
            router.push('/closed-management/entry-exit/personnel-application');
          }
          // if (accessStore.loginExpired) {
          //   accessStore.setLoginExpired(false);
          // } else {
          // }

          // if (userInfo?.realName) {
          //   ElNotification({
          //     message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
          //     title: $t('authentication.loginSuccess'),
          //     type: 'success',
          //   });
          // }
        }
      } finally {
        loginLoading.value = false;
      }

      return {
        userInfo,
      };
    }

    async function logout(redirect: boolean = true) {
      try {
        await logoutApi();
      } catch {
        // 不做任何处理
      }
      resetAllStores();
      accessStore.setLoginExpired(false);

      // 回登陆页带上当前路由地址
      await router.replace({
        path: LOGIN_PATH,
        query: redirect
          ? {
              redirect: encodeURIComponent(router.currentRoute.value.fullPath),
            }
          : {},
      });
    }

    async function fetchUserInfo() {
      let userInfo: null | UserInfo = null;
      userInfo = await getUserInfoApi();
      userStore.setUserInfo(userInfo);
      return userInfo;
    }

    function $reset() {
      loginLoading.value = false;
    }

    const user = ref({
      username: '',
      password: '',
    });

    const setUser = (u) => {
      user.value = u;
    };
    const delUser = () => {
      user.value = undefined;
    };

    return {
      $reset,
      authLogin,
      fetchUserInfo,
      loginLoading,
      logout,
      user,
      setUser,
      delUser,
    };
  },
  {
    persist: true,
  },
);
